﻿using Marten.Internal;
using Marten.Linq.QueryHandlers;
using System.Data.Common;
using Weasel.Postgresql;

namespace Catalog.API.Products.GetProductsByCategory
{
    public record GetProductsByCategoryResult(IEnumerable<Product> Products);

    public record GetProductsByCategoryQuery(string CategoryName) : IQuery<GetProductsByCategoryResult>;

    public class GetProductsByCategoryQueryValidator:AbstractValidator<GetProductsByCategoryQuery>
    {
        public GetProductsByCategoryQueryValidator()
        {
            RuleFor(x => x.CategoryName).NotEmpty().WithMessage("CategoryName is required");
        }

    }
    internal class GetProductsByCategoryQueryHandler(IDocumentSession session) 
        : IQueryHandler<GetProductsByCategoryQuery, GetProductsByCategoryResult>

    {
        public async Task<GetProductsByCategoryResult> Handle(GetProductsByCategoryQuery query, CancellationToken cancellationToken)
        {
           var products=await session.Query<Product>().Where(p=>p.Categories.Contains(query.CategoryName)).ToListAsync(cancellationToken);
           
            return new GetProductsByCategoryResult(products);
        }
    }
}
